package services

import (
	adminDao "TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/app/dao"
	"TaskAssignmentSystem/internal/pkg/modelbase"
	"TaskAssignmentSystem/pkg/db/redis"
	"TaskAssignmentSystem/pkg/timehandler"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
	"unicode"
)

type SystemUserService struct {
}

type UserServiceResponse struct {
	Token string `json:"token"`
}

func (s *SystemUserService) VerifyLogin(userName, passWord string) (result *dao.SystemUser, err error) {
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.CustomWhere = append(systemUserDao.CustomWhere, fmt.Sprintf("user_id = '%s' or phone = '%s' or email = '%s'", userName, userName, userName))
	res, err := systemUserDao.First(map[string]interface{}{})
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	if res.Status == 2 {
		return nil, errors.New("该用户已经被封禁")
	}
	if res.Status == 0 {
		return nil, errors.New("该用户已经被注销")
	}
	if utils.Base64Encode(passWord) != res.PassWord {
		return nil, errors.New("用户密码错误")
	}
	return &res, nil
}

func (s *SystemUserService) Login(userName, passWord string) (data UserServiceResponse, err error) {
	user, err := s.VerifyLogin(userName, passWord)
	if err != nil {
		return data, err
	}
	//判断是否是数据维护期间
	var dictServe services.SystemDictService
	if dataMaintenance, err := dictServe.GetDictByCode("ZXZ_DATA_MAINTENANCE"); err == nil {
		if utils.StringIsNotEmpty(dataMaintenance.DictValue) && utils.StringIsNotEmpty(dataMaintenance.Description) {
			//if dataMaintenance.DictValue.u
			loc, _ := time.LoadLocation("Local") //获取当地时区
			if start, err := time.ParseInLocation("2006-01-02 15:04:05", dataMaintenance.DictValue, loc); err == nil {
				if end, err := time.ParseInLocation("2006-01-02 15:04:05", dataMaintenance.Description, loc); err == nil {
					//当前时间在数据维护期间
					if start.Unix() < time.Now().Unix() && time.Now().Unix() < end.Unix() {
						//查询是否在白名单用户内
						var userWhiteListDao dao.Common[adminDao.SystemUserWhitelist]
						if count, err := userWhiteListDao.Count(map[string]interface{}{"user_id": user.UserId}); err == nil {
							if count == 0 {
								return data, errors.New(fmt.Sprintf("平台维护中，维护时间为：%v 至 %v ，请维护结束再登录", dataMaintenance.DictValue, dataMaintenance.Description))
							}
						}
					}
				}
			}
		}
	}
	var userDao dao.Common[dao.SystemUser]
	userDao.UpdateOne(user.Id, map[string]interface{}{"last_login_time": time.Now()})
	claims := &CustomClaims{}
	claims.Id = user.Id
	claims.UserName = user.UserId
	claims.RealName = user.RealName
	claims.Phone = user.Phone
	//claims.AppSecret = []byte(utils.ServerConf.JwtConf.AppSecret)

	user_token_secret := fmt.Sprintf("%s_%d_%d", utils.ServerConf.JwtConf.AppSecret, user.Id, time.Now().Unix())
	claims.AppSecret = []byte(user_token_secret)
	data.Token, err = claims.SetToken(24 * 60 * 60 * time.Second)
	return
}

func (s *SystemUserService) Logout(id uint) error {
	claims := &CustomClaims{}
	claims.Id = id
	return claims.DelToken()
}

func (s *SystemUserService) UpdatePassWord(id uint, oldPassWord string, set map[string]interface{}) error {
	var systemAdminDao dao.Common[dao.SystemUser]
	systemAdminDao.Query = map[string]interface{}{"id": id}
	if systemAdmin, err := systemAdminDao.First(systemAdminDao.Query); err != nil {
		return err
	} else {
		if systemAdmin.PassWord != utils.Base64Encode(oldPassWord) {
			return errors.New("当前密码错误")
		}
	}
	//新增一条redis记录，为了限制用户一天只能修改一次密码的策略
	expired := timehandler.GetDayStart(time.Now().In(utils.Loc).AddDate(0, 0, 1)).Unix() - time.Now().In(utils.Loc).Unix()
	set_nx := redis.RedisGClient.SetNX(fmt.Sprintf("user_update_password_%d", id), id, time.Duration(expired)*time.Second)
	if res, err := set_nx.Result(); err != nil {
		return err
	} else {
		if !res {
			return errors.New("密码一天只能修改一次")
		} else {
			return systemAdminDao.UpdateOne(id, set).Error
		}
	}
}

func (s *SystemUserService) VerifyEmail(email string) (exist bool, err error) {
	var serve CommonService[dao.SystemUser]
	serve.WhereStr = []string{}
	serve.WhereStr = append(serve.WhereStr, fmt.Sprintf("email = '%s'", email))
	if count, err := serve.Count(); err != nil {
		return false, err
	} else {
		if count == 0 {
			return false, nil
		} else {
			return true, nil
		}
	}
}

func (s *SystemUserService) VerifyPhone(phone string) (exist bool, err error) {
	var serve CommonService[dao.SystemUser]
	serve.WhereStr = []string{}
	serve.WhereStr = append(serve.WhereStr, fmt.Sprintf("phone = '%s'", phone))
	if count, err := serve.Count(); err != nil {
		return false, err
	} else {
		if count == 0 {
			return false, nil
		} else {
			return true, nil
		}
	}
}

type RegisterResponse struct {
	Email    string `json:"email" validate:"required"`
	PassWord string `json:"pass_word" validate:"required"`
}
type RegisterResponseV2 struct {
	Phone    string `json:"phone" validate:"required"`
	PassWord string `json:"pass_word" validate:"required"`
}

func (s *SystemUserService) Register(email, passWord, code, team string) (data RegisterResponse, err error) {
	//密码非空校验
	if passWord == "" {
		return data, errors.New("密码不能为空")
	}

	//校验邮箱是否注册
	exist, err := s.VerifyEmail(email)
	if err != nil {
		return data, err
	}
	if exist {
		return data, errors.New("该邮箱已注册")
	}
	//校验验证码
	codeKey := fmt.Sprintf("%s_email_register_code", email)
	redisCodeRes := redis.RedisGClient.Get(codeKey)
	if redisCodeRes.Err() != nil {
		return data, errors.New("验证码失效，请重新获取验证码!")
	}
	redisCode := redisCodeRes.Val()
	if code != redisCode {
		return data, errors.New("验证码输入错误，请重新输入验证码!")
	}

	var dictServe SystemDictService
	//注册账户
	var record modelbase.SystemUser
	record.PassWord = utils.Base64Encode(passWord)
	record.Email = email
	userId := ""
	if pp, err := dictServe.GetValueByCode("ZXZ_BRAND"); err != nil {
		return data, errors.New("宅小职品牌获取失败")
	} else {
		userId += pp
		record.UserNamePrefix = pp
	}
	if utils.StringIsEmpty(team) {
		team, err = dictServe.GetValueByCode("ZXZ_DEFAULT_TEAM")
		if err != nil {
			return data, errors.New("宅小职团队获取失败")
		}
	} else {
		teamIndex := -1
		for i, v := range team {
			if unicode.Is(unicode.Han, v) { // 中文字符
				teamIndex = i
				break
			}
		}
		if teamIndex != -1 {
			teamWithOutCn := team[:teamIndex]
			teamWithOutCn = strings.TrimSpace(teamWithOutCn)
			teamWithOutCn = strings.Replace(teamWithOutCn, "%2B", "", -1)
			teamWithOutCn = strings.Replace(teamWithOutCn, "%20", "", -1)
			team = teamWithOutCn
		}
	}
	record.TeamNumber = team
	userId += team
	if userNum, err := dictServe.GetUserNumber(); err != nil {
		return data, errors.New("宅小职用户编号获取失败")
	} else {
		userId += userNum
		record.UserNumber = userNum
	}
	record.UserId = userId
	record.Status = 1
	//record.NickName = s.getNickName(email)
	var prohibitedWordsService services.SystemProhibitedWordsService
	record.NickName = prohibitedWordsService.GenerateRandomNickName(10)
	var systemUserDao dao.Common[modelbase.SystemUser]
	if err := systemUserDao.CreateOne(record).Error; err != nil {
		return data, err
	}

	// 注册的账户存入 Chan
	if user, err := s.VerifyLogin(email, passWord); err != nil {
		return data, errors.New("服务器异常！")
	} else {
		PutSystemUserChan(*user)
	}
	//返回账户密码到前端
	data.Email = email
	data.PassWord = passWord
	return data, err
}

func (s *SystemUserService) RegisterPhone(phone, passWord, code, team string) (data RegisterResponseV2, err error) {
	//密码非空校验
	if passWord == "" {
		return data, errors.New("密码不能为空")
	}
	//校验验证码
	codeKey := fmt.Sprintf("%s_phone_reset_new_phone_code", phone)
	redisCodeRes := redis.RedisGClient.Get(codeKey)
	if redisCodeRes.Err() != nil {
		return data, errors.New("验证码失效，请重新获取验证码!")
	}
	redisCode := redisCodeRes.Val()
	if code != redisCode {
		return data, errors.New("验证码输入错误，请重新输入验证码!")
	}

	var dictServe SystemDictService
	//注册账户
	var record modelbase.SystemUser
	record.PassWord = utils.Base64Encode(passWord)
	record.Phone = phone
	userId := ""
	if pp, err := dictServe.GetValueByCode("ZXZ_BRAND"); err != nil {
		return data, errors.New("宅小职品牌获取失败")
	} else {
		userId += pp
		record.UserNamePrefix = pp
	}
	if utils.StringIsEmpty(team) {
		team, err = dictServe.GetValueByCode("ZXZ_DEFAULT_TEAM")
		if err != nil {
			return data, errors.New("宅小职团队获取失败")
		}
	} else {
		teamIndex := -1
		for i, v := range team {
			if unicode.Is(unicode.Han, v) { // 中文字符
				teamIndex = i
				break
			}
		}
		if teamIndex != -1 {
			teamWithOutCn := team[:teamIndex]
			teamWithOutCn = strings.TrimSpace(teamWithOutCn)
			teamWithOutCn = strings.Replace(teamWithOutCn, "%2B", "", -1)
			teamWithOutCn = strings.Replace(teamWithOutCn, "%20", "", -1)
			team = teamWithOutCn
		}
	}
	record.TeamNumber = team
	userId += team
	if userNum, err := dictServe.GetUserNumber(); err != nil {
		return data, errors.New("宅小职用户编号获取失败")
	} else {
		userId += userNum
		record.UserNumber = userNum
	}
	record.UserId = userId
	record.Status = 1
	//record.NickName = s.getNickName(email)
	var prohibitedWordsService services.SystemProhibitedWordsService
	record.NickName = prohibitedWordsService.GenerateRandomNickName(10)
	var systemUserDao dao.Common[modelbase.SystemUser]
	if err := systemUserDao.CreateOne(record).Error; err != nil {
		return data, err
	}

	// 注册的账户存入 Chan
	if user, err := s.VerifyLogin(phone, passWord); err != nil {
		return data, errors.New("服务器异常！")
	} else {
		PutSystemUserChan(*user)
	}
	//返回账户密码到前端
	data.Phone = phone
	data.PassWord = passWord
	return data, err
}

// 初始化昵称，取 email @ 之前的字符串，再加随机6位数字
func (s *SystemUserService) getNickName(email string) string {
	comma := strings.Index(email, "@")
	return email[:comma] + utils.RandNumCodeToString(6)
}

func (s *SystemUserService) ResetPwdEmailConfirmCode(email, code string) error {
	//校验邮箱是否注册
	exist, err := s.VerifyEmail(email)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("请确认邮箱是否正确！")
	}
	//校验验证码
	codeKey := fmt.Sprintf("%s_email_reset_pwd_code", email)
	redisCodeRes := redis.RedisGClient.Get(codeKey)
	if redisCodeRes.Err() != nil {
		return errors.New("验证码失效，请重新获取验证码!")
	}
	redisCode := redisCodeRes.Val()
	if code != redisCode {
		return errors.New("验证码输入错误，请重新输入验证码!")
	}
	return nil
}

func (s *SystemUserService) ResetPwdEmail(email, passWord, code string) error {
	//密码非空校验
	if passWord == "" {
		return errors.New("密码不能为空")
	}

	//校验邮箱是否注册
	exist, err := s.VerifyEmail(email)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("该邮箱未注册")
	}
	//校验一天改一次密码
	timeKey := fmt.Sprintf("%s_email_reset_pwd_time", email)
	if err := redis.RedisGClient.Get(timeKey).Err(); err == nil {
		return errors.New("24小时内只能修改一次密码!")
	}

	//校验验证码
	codeKey := fmt.Sprintf("%s_email_reset_pwd_code", email)
	redisCodeRes := redis.RedisGClient.Get(codeKey)
	if redisCodeRes.Err() != nil {
		return errors.New("验证码失效，请重新获取验证码!")
	}
	redisCode := redisCodeRes.Val()
	if code != redisCode {
		return errors.New("验证码输入错误，请重新输入验证码!")
	}

	//修改密码
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"email": email}
	systemUserDao.Update(map[string]interface{}{"pass_word": utils.Base64Encode(passWord)})

	//修改密码成功后，设置修改时间到redis
	err = redis.RedisGClient.Set(timeKey, time.Now(), 24*60*60*time.Second).Err() //修改密码，频率，24小时一次
	if err != nil {
		return err
	}
	return nil
}

func (s *SystemUserService) ResetPwdPhoneConfirmCode(phone, code string) error {
	//校验手机号是否注册
	exist, err := s.VerifyPhone(phone)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("请确认手机号是否正确！")
	}
	//校验验证码
	codeKey := fmt.Sprintf("%s_phone_reset_pwd_code", phone)
	redisCodeRes := redis.RedisGClient.Get(codeKey)
	if redisCodeRes.Err() != nil {
		return errors.New("验证码失效，请重新获取验证码!")
	}
	redisCode := redisCodeRes.Val()
	if code != redisCode {
		return errors.New("验证码输入错误，请重新输入验证码!")
	}
	return nil
}

func (s *SystemUserService) ResetPwdPhone(phone, passWord, code string) error {
	//密码非空校验
	if passWord == "" {
		return errors.New("密码不能为空")
	}

	//校验手机号是否注册
	exist, err := s.VerifyPhone(phone)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("该手机号未注册")
	}
	//校验一天改一次密码
	timeKey := fmt.Sprintf("%s_phone_reset_pwd_time", phone)
	if err := redis.RedisGClient.Get(timeKey).Err(); err == nil {
		return errors.New("24小时内只能修改一次密码!")
	}

	//校验验证码
	codeKey := fmt.Sprintf("%s_phone_reset_pwd_code", phone)
	redisCodeRes := redis.RedisGClient.Get(codeKey)
	if redisCodeRes.Err() != nil {
		return errors.New("验证码失效，请重新获取验证码!")
	}
	redisCode := redisCodeRes.Val()
	if code != redisCode {
		return errors.New("验证码输入错误，请重新输入验证码!")
	}

	//修改密码
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"phone": phone}
	systemUserDao.Update(map[string]interface{}{"pass_word": utils.Base64Encode(passWord)})

	//修改密码成功后，设置修改时间到redis
	err = redis.RedisGClient.Set(timeKey, time.Now(), 24*60*60*time.Second).Err() //修改密码，频率，24小时一次
	if err != nil {
		return err
	}
	return nil
}

type UserInfoResponse struct {
	dao.SystemUser
	RealNameAuthenticationRule string `json:"realNameAuthenticationRule"`
	AvatarRule                 string `json:"avatarRule"`
	IntroductionRule           string `json:"introductionRule"`
	NickNameRule               string `json:"nickNameRule"`
	DeliveryAddressRule        string `json:"deliveryAddressRule"`
	AlipayAccountRule          string `json:"alipayAccountRule"`
	PhoneRule                  string `json:"phoneRule"`
	EmailRule                  string `json:"emailRule"`
	HasUnreadMessage           bool   `json:"hasUnreadMessage"`
	UserInfoIsFull             bool   `json:"userInfoIsFull"`
	IsTeamLeader               bool   `json:"isTeamLeader"`
}

func (s *SystemUserService) UserInfo(id uint) (data UserInfoResponse, err error) {
	var userDao dao.Common[dao.SystemUser]
	if user, err := userDao.First(map[string]interface{}{"id": id}); err != nil {
		return data, err
	} else {
		//获取用户各个字段规则
		res := UserInfoResponse{SystemUser: user}
		//保护用户隐私，身份证照片路径不返回到前端
		res.IdCardFace = ""
		res.IdCardBack = ""

		var dictServe SystemDictService
		realNameAuthenticationRule, err := dictServe.GetDictByCode("ZXZ_USER_REAL_NAME_AUTHENTICATION")
		if err != nil {
			return data, errors.New("获取实名认证规则失败")
		}
		res.RealNameAuthenticationRule = realNameAuthenticationRule.Description

		avatarRule, err := dictServe.GetDictByCode("ZXZ_USER_AVATAR_EDIT")
		if err != nil {
			return data, errors.New("获取头像修改规则失败")
		}
		res.AvatarRule = avatarRule.Description

		introductionRule, err := dictServe.GetDictByCode("ZXZ_USER_INTRODUCTION_EDIT")
		if err != nil {
			return data, errors.New("获取简介修改规则失败")
		}
		res.IntroductionRule = introductionRule.Description

		nickNameRule, err := dictServe.GetDictByCode("ZXZ_USER_NICK_NAME_EDIT")
		if err != nil {
			return data, errors.New("获取昵称修改规则失败")
		}
		res.NickNameRule = nickNameRule.Description

		deliveryAddressRule, err := dictServe.GetDictByCode("ZXZ_USER_DELIVERY_ADDRESS_EDIT")
		if err != nil {
			return data, errors.New("获取收货地址修改规则失败")
		}
		res.DeliveryAddressRule = deliveryAddressRule.Description

		alipayAccountRule, err := dictServe.GetDictByCode("ZXZ_USER_ALIPAY_ACCOUNT_EDIT")
		if err != nil {
			return data, errors.New("获取支付宝账户修改规则失败")
		}
		res.AlipayAccountRule = alipayAccountRule.Description

		phoneRule, err := dictServe.GetDictByCode("ZXZ_USER_PHONE_EDIT")
		if err != nil {
			return data, errors.New("获取头像修改规则失败")
		}
		res.PhoneRule = phoneRule.Description

		emailRule, err := dictServe.GetDictByCode("ZXZ_USER_EMAIL_EDIT")
		if err != nil {
			return data, errors.New("获取邮箱修改规则失败")
		}
		res.EmailRule = emailRule.Description
		//检查用户信息是否完善
		if utils.StringIsEmpty(user.Email) || utils.StringIsEmpty(user.Phone) {
			//Email 和 Phone 有一个未设置，则视为用户信息不全，提示小红点
			res.UserInfoIsFull = false
		} else {
			res.UserInfoIsFull = true
		}
		//查询用户未读消息
		var userMessageServe UserMessageService
		if hasUnreadMessage, err := userMessageServe.CheckUserHasUnreadMessage(id); err != nil {
			return data, errors.New("读取用户未读消息失败")
		} else {
			res.HasUnreadMessage = hasUnreadMessage
		}
		var adminCommon adminDao.Common[dao.SystemUser]
		countSql := fmt.Sprintf("SELECT count(*) AS total FROM tas_system_team WHERE user_id = '%s'", user.UserId)
		count, err := adminCommon.RawCount(countSql, "total")
		if err != nil {
			return res, err
		}
		if count == 1 {
			res.IsTeamLeader = true
		} else {
			res.IsTeamLeader = false
		}
		return res, nil
	}
}

func (s *SystemUserService) FindUserInfoOnly(id uint) (dao.SystemUser, error) {
	var userDao dao.Common[dao.SystemUser]
	return userDao.First(map[string]interface{}{"id": id})
}

func (s *SystemUserService) VerifyUser(id uint) (exist bool, err error) {
	var serve CommonService[dao.SystemUser]
	serve.Query = map[string]interface{}{"id": id}
	if count, err := serve.Count(); err != nil {
		return false, err
	} else {
		if count == 0 {
			return false, nil
		} else {
			return true, nil
		}
	}
}

func (s *SystemUserService) UserEditSettings(id uint, param map[string]string) error {
	//校验用户是否存在
	exist, err := s.VerifyUser(id)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("该用户不存在")
	}

	user, err := s.FindUserInfoOnly(id)
	if err != nil {
		return err
	}
	var dictServe SystemDictService
	rule, err := dictServe.GetDictByCode(param["dictCode"])
	if err != nil {
		return errors.New("获取修改规则失败")
	}
	days, _ := strconv.Atoi(rule.DictValue)
	var timeExpiration = time.Duration(days) * 24 * 60 * 60 * time.Second

	//校验一天改一次密码
	timeKey := fmt.Sprintf("%s_user_reset_%s_time", user.UserId, param["timeKey"])
	if err := redis.RedisGClient.Get(timeKey).Err(); err == nil {
		return errors.New(rule.Description)
	}

	//更新用户数据
	upType := param["upType"]
	if upType == "1" {
		//1:实名认证
		if err = s.UserRealNameAuthentication(id, user, param["realName"], param["idCardNumber"], user.IdCardFace, rule.Description, rule.DictNumber); err != nil {
			return err
		}
		var teamDao dao.Common[adminDao.SystemTeam]
		teamDao.Query = map[string]interface{}{"user_id": id}
		teamDao.Update(map[string]interface{}{"user_name": param["realName"]})
		return nil
	} else if upType == "2" {
		//2:修改邮箱,使用原邮箱修改
		if user.Email != param["oldEmail"] {
			return errors.New("原邮箱与登录账户不匹配！")
		}
		if err = s.UserEditEmailByEmail(id, param["oldEmail"], param["newEmail"], param["oldCode"], param["newCode"]); err != nil {
			return err
		}
	} else if upType == "3" {
		//3:修改邮箱,使用原手机号修改
		if user.Phone != param["oldPhone"] {
			return errors.New("原手机号与登录账户不匹配！")
		}
		if err = s.UserEditEmailByPhone(id, param["oldPhone"], param["newEmail"], param["oldCode"], param["newCode"]); err != nil {
			return err
		}
	} else if upType == "4" {
		//4:修改手机号,使用原手机号修改
		if user.Phone != param["oldPhone"] {
			return errors.New("原手机号与登录账户不匹配！")
		}
		if err = s.UserEditPhoneByPhone(id, param["oldPhone"], param["newPhone"], param["oldCode"], param["newCode"]); err != nil {
			return err
		}
	} else if upType == "5" {
		//5:修改手机号,使用原邮箱修改
		if user.Email != param["oldEmail"] {
			return errors.New("原邮箱与登录账户不匹配！")
		}
		if err = s.UserEditPhoneByEmail(id, param["oldEmail"], param["newPhone"], param["oldCode"], param["newCode"]); err != nil {
			return err
		}
	} else if upType == "6" {
		//6:修改支付宝账户
		s.UserEditAlipayAccount(id, param["alipay_account"])
	} else if upType == "7" {
		//7:修改收货地址
		s.UserEditDeliveryAddress(id, param["delivery_address"])
	} else if upType == "8" {
		//8:修改昵称
		if err = s.UserEditNickName(id, param["nick_name"]); err != nil {
			return err
		}
		var teamDao dao.Common[adminDao.SystemTeam]
		teamDao.Query = map[string]interface{}{"user_id": user.UserId}
		if err := teamDao.Update(map[string]interface{}{"nick_name": param["nick_name"]}).Error; err != nil {
			return err
		}
	} else if upType == "9" {
		//9:修改简介
		if err = s.UserEditIntroduction(id, param["introduction"]); err != nil {
			return err
		}
	} else {
		return errors.New("类型异常")
	}

	//修改成功后，设置修改时间到redis
	err = redis.RedisGClient.Set(timeKey, time.Now(), timeExpiration).Err()
	if err != nil {
		return err
	}
	return nil
}

func (s *SystemUserService) UserRealNameAuthentication(id uint, user dao.SystemUser, realName, idCardNumber, idCardFace, limitAgeDes string, limitAge int) error {
	/*res, err := utils.OCRFace(idCardFace)
	if err != nil {
		return err
	}
	if realName != res["name"] {
		return errors.New("真实姓名输入错误！")
	}
	if idCardNumber != res["idNumber"] {
		return errors.New("身份证号码输入错误！")
	}
	birthDate := res["birthDate"]
	birthDateArr := strings.Split(birthDate, "年")
	year := strings.ReplaceAll(birthDateArr[0], " ", "")
	yearNum, _ := strconv.Atoi(year)
	yearNum += limitAge
	nowYear := time.Now().Year()
	if nowYear < yearNum {
		return errors.New(limitAgeDes)
	}*/
	var systemUserDao dao.Common[dao.SystemUser]
	//判断该身份证号是否已经认证过
	if count, err := systemUserDao.Count(map[string]interface{}{"id_card_number": idCardNumber, "is_authentication": 1}); err != nil {
		return err
	} else {
		if count > 0 {
			return errors.New("您的身份证已被认证，请切换已认证账号，如需解绑认证账号或找回认证账号，请发送问题到邮箱zzm@njmsxzxwwgc999.onexmail.com咨询处理")
		}
	}
	//更新用户数据
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"real_name": realName, "id_card_number": idCardNumber, "is_authentication": 1})

	//存入chan，触发团队中的相关后续操作
	PutSystemUserChan(user)

	return nil
}

func (s *SystemUserService) UserEditEmailByEmail(id uint, oldEmail, newEmail, oldCode, newCode string) error {
	oldCodeKey := fmt.Sprintf("%s_email_reset_old_email_code", oldEmail)
	oldCodeKeyRes := redis.RedisGClient.Get(oldCodeKey)
	if oldCodeKeyRes.Err() != nil {
		return errors.New("原邮箱验证码获取失败!")
	}
	if oldCodeKeyRes.Val() != oldCode {
		return errors.New("原邮箱验证码输入错误!")
	}

	newCodeKey := fmt.Sprintf("%s_email_reset_new_email_code", newEmail)
	newCodeKeyRes := redis.RedisGClient.Get(newCodeKey)
	if newCodeKeyRes.Err() != nil {
		return errors.New("新邮箱验证码获取失败!")
	}
	if newCodeKeyRes.Val() != newCode {
		return errors.New("新邮箱验证码输入错误!")
	}

	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"email": newEmail})
	return nil
}

func (s *SystemUserService) UserEditEmailByPhone(id uint, oldPhone, newEmail, oldCode, newCode string) error {
	oldCodeKey := fmt.Sprintf("%s_email_reset_old_phone_code", oldPhone)
	oldCodeKeyRes := redis.RedisGClient.Get(oldCodeKey)
	if oldCodeKeyRes.Err() != nil {
		return errors.New("原手机验证码获取失败!")
	}
	if oldCodeKeyRes.Val() != oldCode {
		return errors.New("原手机验证码输入错误!")
	}

	newCodeKey := fmt.Sprintf("%s_email_reset_new_email_code", newEmail)
	newCodeKeyRes := redis.RedisGClient.Get(newCodeKey)
	if newCodeKeyRes.Err() != nil {
		return errors.New("新邮箱验证码获取失败!")
	}
	if newCodeKeyRes.Val() != newCode {
		return errors.New("新邮箱验证码输入错误!")
	}

	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"email": newEmail})
	return nil
}

func (s *SystemUserService) UserEditPhoneByPhone(id uint, oldPhone, newPhone, oldCode, newCode string) error {
	oldCodeKey := fmt.Sprintf("%s_phone_reset_old_phone_code", oldPhone)
	oldCodeKeyRes := redis.RedisGClient.Get(oldCodeKey)
	if oldCodeKeyRes.Err() != nil {
		return errors.New("原手机验证码获取失败!")
	}
	if oldCodeKeyRes.Val() != oldCode {
		return errors.New("原手机验证码输入错误!")
	}

	newCodeKey := fmt.Sprintf("%s_phone_reset_new_phone_code", newPhone)
	newCodeKeyRes := redis.RedisGClient.Get(newCodeKey)
	if newCodeKeyRes.Err() != nil {
		return errors.New("新手机验证码获取失败!")
	}
	if newCodeKeyRes.Val() != newCode {
		return errors.New("新手机验证码输入错误!")
	}

	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"phone": newPhone})
	return nil
}

func (s *SystemUserService) UserEditPhoneByEmail(id uint, oldEmail, newPhone, oldCode, newCode string) error {
	oldCodeKey := fmt.Sprintf("%s_phone_reset_old_email_code", oldEmail)
	oldCodeKeyRes := redis.RedisGClient.Get(oldCodeKey)
	if oldCodeKeyRes.Err() != nil {
		return errors.New("原邮箱验证码获取失败!")
	}
	if oldCodeKeyRes.Val() != oldCode {
		return errors.New("原邮箱验证码输入错误!")
	}

	newCodeKey := fmt.Sprintf("%s_phone_reset_new_phone_code", newPhone)
	newCodeKeyRes := redis.RedisGClient.Get(newCodeKey)
	if newCodeKeyRes.Err() != nil {
		return errors.New("新手机验证码获取失败!")
	}
	if newCodeKeyRes.Val() != newCode {
		return errors.New("新手机验证码输入错误!")
	}

	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"phone": newPhone})
	return nil
}

func (s *SystemUserService) UserEditAlipayAccount(id uint, alipayAccount string) {
	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"alipay_account": alipayAccount})
}

func (s *SystemUserService) UserEditDeliveryAddress(id uint, deliveryAddress string) {
	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"delivery_address": deliveryAddress})
}

func (s *SystemUserService) UserEditNickName(id uint, nickName string) error {

	var prohibitedWordsService services.SystemProhibitedWordsService
	if _, isProhibited, err := prohibitedWordsService.CheckProhibitedWords(nickName); err != nil {
		return err
	} else {
		if isProhibited {
			//return errors.New("昵称包含违禁词：" + strings.Join(words, ","))
			return errors.New("昵称违规，无法使用")
		}
	}
	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	//先查重
	if count, err := systemUserDao.Count(map[string]interface{}{"nick_name": nickName}); err != nil {
		return err
	} else {
		if count > 0 {
			return errors.New("昵称重复，无法使用")
		}
	}
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"nick_name": nickName})
	return nil
}

func (s *SystemUserService) UserEditIntroduction(id uint, introduction string) error {
	var prohibitedWordsService services.SystemProhibitedWordsService
	if _, isProhibited, err := prohibitedWordsService.CheckProhibitedWords(introduction); err != nil {
		return err
	} else {
		if isProhibited {
			//return errors.New("简介包含违禁词：" + strings.Join(words, ","))
			return errors.New("简介违规，无法使用")
		}
	}

	//更新用户数据
	var systemUserDao dao.Common[dao.SystemUser]
	systemUserDao.Query = map[string]interface{}{"id": id}
	systemUserDao.Update(map[string]interface{}{"introduction": introduction})
	return nil
}
